package org.example.service;

import org.example.exception.AppException;
import org.example.mapper.UserMapper;
import org.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User selectOne(User params) {
        return userMapper.selectOne(params);
    }

    public List<User> query() {
        return userMapper.selectAll();
    }

    //新增用户（注册）：先根据账号查询一个用户，如果查不到，才插入，否则就报错
    //这个业务，涉及2个sql：先查，在插入，并发场景下，可能会出现问题
    //需要添加事务
    @Transactional
    public int register(User user) {
        User params = new User();//作为查询条件
        params.setUsername(user.getUsername());
        User exists = userMapper.selectOne(params);
        if (exists != null) {
            throw new AppException("用户已存在");
        }
        //不存在，才能插入
        return userMapper.insertSelective(user);
    }

    public User queryById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public int update(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    public int delete(List<Integer> ids) {
        return userMapper.deleteByIds(ids);
    }
}
